<template>
  <FaLayout v-loading="loading" class="page" :right="240" :left="240">
    <AppHeader slot="header">
      <ElPopover placement="left-start" style="margin-right: 16px">
        <ElButton slot="reference">选项</ElButton>

        <SettingPop :data="setting" />
      </ElPopover>

      <ElButton type="primary" :loading="loading" @click="submit">保存</ElButton>
    </AppHeader>

    <div slot="left" class="page-left">
      <FaPanel title="参与方">
        <FaActors :actors="actors" :selected.sync="activeActor" :widgets="widgets" />
      </FaPanel>

      <FaPanel title="签署控件" v-show="!activeActor || activeActor.sign !== false">
        <FaWidgets :actor="activeActor" widget-style="sign" />
      </FaPanel>

      <FaPanel title="填写控件" v-show="!activeActor || activeActor.fill !== false">
        <FaWidgets :actor="activeActor" widget-style="fill" />
      </FaPanel>
    </div>

    <FaContract
      ref="viewer"
      :docs="docs"
      :doc-index.sync="docIndex"
      :page-src="getPageImg"
      :widget="setting.widget"
      :riding="setting.riding"
      :droppable="setting.droppable"
      :widget-moving-across-pages="setting.widgetMovingAcrossPages"
      :widget-actor-required="setting.widgetActorRequired"
      :widgets="widgets"
    />

    <template #right>
      <FaPanel :title="`设置${activeWidget.option.name}`" v-if="activeWidget" @click.stop.native style="height: 100%">
        <FaWidgetSetting :viewer="viewer" :data="activeWidget" :actors="actors" :actor-disable="actorDisable" />
      </FaPanel>

      <FaThumbs v-show="!activeWidget" :viewer="viewer" :docs="docs" :doc-index.sync="docIndex" />
    </template>
  </FaLayout>
</template>

<script lang="ts">
import { computed, defineComponent, onMounted, reactive, Ref, ref, toRefs } from 'vue'
import { Message, MessageBox } from 'element-ui'
import { WidgetMode, ActorData, Widget, DocData, Viewer, RawField, PageData } from 'fdd-contract'
import AppHeader from '../components/AppHeader.vue'
import SettingPop, { setting } from '../components/SettingPop.vue'
import { mockAjax } from '../utils'
import { getDetail, getPageImg } from '../utils/mock'

const WIDGET_STORE_KEY = 'set-widget-raws'

/** 获取本地存储控件 */
function getWidgets(actors: ActorData[]) {
  const raws: RawField[] = JSON.parse(sessionStorage.getItem(WIDGET_STORE_KEY) || '[]') || []

  return raws.map(item =>
    Widget.createRawWidget(item, {
      mode: WidgetMode.SET,
      docId: item.docId,
      actor: item.actorId ? actors.find(actor => actor.id === item.actorId) : undefined
    })
  )
}

/** 保存控件 */
function saveWidgets(widgets: Widget[]) {
  sessionStorage.setItem(
    WIDGET_STORE_KEY,
    JSON.stringify(
      widgets.map(item => {
        return Object.assign(item.getRawField(), {
          docId: item.docId,
          actorId: item.actor.id
        })
      })
    )
  )
}

/** 控件设置 */
export default defineComponent({
  name: 'WidgetSet',
  components: { AppHeader, SettingPop },

  setup() {
    /** 合同控件 */
    const viewer = ref(null) as Ref<Viewer | null>

    /** 详情数据 */
    const detail = reactive({
      docs: [] as DocData[],
      actors: [] as ActorData[],
      widgets: [] as Widget[]
    })

    /** 加载中 */
    const loading = ref(false)

    /** 当前文档索引 */
    const docIndex = ref(0)

    /** 激活的控件 */
    const activeWidget = computed(() => viewer.value?.activeWidget || null)

    /** 激活的参与方 */
    const activeActor = ref(undefined as undefined | ActorData)

    /** 详情加载 */
    async function load() {
      try {
        loading.value = true

        const { docs, actors } = await getDetail()

        Object.assign(detail, { docs, actors })

        detail.widgets = getWidgets(actors)
      } finally {
        loading.value = false
      }
    }

    onMounted(load)

    return {
      ...toRefs(detail),

      /** 合同控件 */
      viewer,

      /** 加载中 */
      loading,

      /** 当前文档索引 */
      docIndex,

      /** 获取文档页面图片地址 */
      getPageImg /* (doc: DocData, page: PageData) {
        return `/api/userCenter/api/v1/sign-task/file/get-pic/866cc7a413bdc9538b91f80494faeaebfe2ada252418a5d62c8b5ade8e81123e15727504b7c5e25aef8d42ed4618a9267b729123d40715e29a1c020a337e3cad_${page.p}`
      } */,

      /** 激活的控件 */
      activeWidget,

      /** 激活的参与方 */
      activeActor,

      /** 是否禁用参与方 */
      actorDisable: (item: ActorData) => item.index >= 4,

      /** 设置 */
      setting: ref({ ...setting }),

      /** 详情加载 */
      load,

      /** 提交 */
      async submit() {
        await viewer.value?.validate()

        await mockAjax(() => saveWidgets(detail.widgets))

        Message.success('保存成功')

        load()
      }
    }
  }
})
</script>

<style lang="scss" scoped>
.page-left {
  height: 100%;
  overflow: auto;
}
</style>
